// 这是一个线程分离测试
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <error.h>
#include "restart.h"

#define BUFSIZE 1024

/* 处理来自文件描述符的read命令*/
void *processfd(void *arg) {
    char buf[BUFSIZE];
    int fd;
    ssize_t nbytes;

    fd = *((int*)(arg) );
    for (;;) {
        if (nbytes = r_read(fd, buf, BUFSIZE) <= 0)
            break;
        printf("文件读取成功");
    }
    
    return NULL;
}

/* 当detachfun作为线程被执行时，会将自己分离出去*/
void *detachfun(void *arg) {
    int i = *((int *)(arg));
    /* 将自己分离出去*/
    if (!pthread_detach(pthread_self())) {
        fprintf(stderr, "Failed to pthread_detac(self)\n");
        return NULL;
    }
    fprintf(stderr, "My argument is %d\n", i);
    return NULL;
}

int main() {
    int error, fd;
    pthread_t tid;

    if (error = pthread_create(&tid, NULL, processfd, &fd)) {
        fprintf(stderr, "Failed to create thread: %s\n", strerror(error));
    } else {
        fprintf(stderr, "---------------线程创建成功-----------\n");
        if (error = pthread_detach(tid))
            fprintf(stderr, "Failed to detach thread: %s\n", strerror(error));
        else fprintf(stderr, "-------------线程分离成功-----------------\n");
    }

    return 0;
}
